/**
 * 
 */
package net.yangying.androidframework.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

/**
 * @author yangying
 * @date 2013-5-31 下午2:26:30
 * @version 1.0
 *
 */
public class AsyncImageLoadThreadManager /*implements ObservableAdapter */{

	private static final String TAG = AsyncImageLoadThreadManager.class.getSimpleName();
	
	// 为了加快速度，在内存中开启缓存（主要应用于重复图片较多时，或者同一个图片要多次被访问，比如在ListView时来回滚动）
	public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
	private ExecutorService executorService = Executors.newFixedThreadPool(2); // 固定五个线程来执行任务
	private final Handler handler = new Handler();
	private RemoteResourceManager mRrm;
    
	public AsyncImageLoadThreadManager(Context context){
//		this.mRrm = context.getRemoteResourceManager();
	}
	
	public Drawable getStoreFromCache(String imageUrl){
		Uri uri = Uri.parse(imageUrl);
		if(mRrm.exists(uri)){
			try {
				return Drawable.createFromStream(mRrm.getInputStream(uri),"image.png");
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
		return null;
	}
	public Drawable loadDrawable(final String imageUrl,final ImageCallback callback) {
		// 如果缓存过就从缓存中取出数据
		if(imageUrl == null){
			return null;
		}
		final String  md5url = MD5Utils.md5(imageUrl);
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(md5url);
			if (softReference.get() != null) {
				return softReference.get();
			}
		}
		// 缓存中没有图像，则从网络上取出数据，并将取出的数据缓存到内存中
		executorService.submit(new Runnable() {
			public void run() {
				try {
					final Drawable drawable = loadImageFromUrl(imageUrl);
					imageCache.put(md5url, new SoftReference<Drawable>(drawable));
					handler.post(new Runnable() {
						public void run() {
							callback.imageLoaded(drawable);
						}
					});
				} catch (Exception e) {
//					throw new RuntimeException(e);
					Log.e(TAG,""+e.getMessage());
				}
			}
		});
		return null;
	}

	// 从网络上取数据方法
	protected Drawable loadImageFromUrl(String imageUrl) {
		try {
			// 测试时，模拟网络延时，实际时这行代码不能有
//			SystemClock.sleep(2000);
			Uri uri = Uri.parse(imageUrl);
			if(mRrm.exists(uri)){
				return Drawable.createFromStream(mRrm.getInputStream(uri),"image.png");
			}
			InputStream is = new URL(imageUrl).openStream();
			mRrm.store(uri, is);
//			Drawable d = Drawable.createFromStream(is,"image.png");
//			BitmapDrawable bitDw = ((BitmapDrawable) d);
//			Bitmap bitmap = bitDw.getBitmap();
//			ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
//			bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
//		    System.out.println("........length......"+baos.toByteArray());
//		    ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
			return Drawable.createFromStream(mRrm.getInputStream(uri),"image.png");
		} catch (Exception e) {
//			throw new RuntimeException(e);
		}
		return null;
	}

	// 对外界开放的回调接口
	public interface ImageCallback {
		//注意 此方法是用来设置目标对象的图像资源
		public void imageLoaded(Drawable imageDrawable);
	}

}